package com.tange.module.device.info;

import com.tange.core.backend.service.response.RxResponse;
import com.tg.appcommon.android.TGLog;
import com.tange.core.backend.service.http.ClientObserver;

import io.reactivex.ObservableEmitter;

/**
 * 通用的网络请求回调
 * @param <T>
 */
public class RxServiceQueryCallback<T> extends ClientObserver<T> {

    private static final String TAG = DeviceInfoServiceManager.TAG + "ServiceQueryCallback";

    private final ObservableEmitter<RxResponse<T>> emitter;

    public RxServiceQueryCallback(ObservableEmitter<RxResponse<T>> emitter) {
        this.emitter = emitter;
    }

    @Override
    protected void onSuccess(T item) {

        TGLog.i(TAG, "[query][onSuccess] item = " + item);

        if (emitter == null || emitter.isDisposed()) {
            TGLog.i(TAG, "[query][onSuccess] emitter invalid");
            return;
        }

        emitter.onNext(RxResponse.createSuccess(item));
    }

    @Override
    protected void onResponseError(int errorCode, String errorInfo) {
        String msg = "errorCode = " + errorCode + " , errorInfo = " + errorInfo;
        TGLog.i(TAG, "[query][onResponseError] " + msg);
        if (emitter == null || emitter.isDisposed()) {
            TGLog.i(TAG, "[query][onResponseError] emitter invalid");
            return;
        }

        emitter.onNext(RxResponse.createFailed(msg));
    }

    @Override
    protected void onOtherError(String error) {
        TGLog.i(TAG, "[query][onOtherError] " + error);
        if (emitter == null || emitter.isDisposed()) {
            TGLog.i(TAG, "[query][onOtherError] emitter invalid");
            return;
        }
        emitter.onNext(RxResponse.createFailed(error));
    }
}
